<template>
  <div class="app-container">
    <el-form
      ref="positionFormRef"
      :model="positionForm"
      label-width="100px"
      :rules="rules"
    >
      <el-card>
        <h4>发布职位</h4>
        <el-alert title="" class="Tips_text">
          <img src="@/assets/common/警告.png" alt="" style="margin: 0 10px" />
          亲爱的HR，您的帐号可同时发布 20 个职位，现已发布 1 个职位。
        </el-alert>
        <div style="padding: 20px 0; font-size: 16px">基本信息</div>
        <el-form-item label="职位名称" prop="jobname">
          <el-input
            v-model="positionForm.jobname"
            placeholder="请输入职位名称"
            style="width: 35%"
          ></el-input>
        </el-form-item>
        <el-form-item label="职位性质" prop="nature">
          <el-radio-group v-model="positionForm.nature">
            <el-radio :label="1" :value="1">全职</el-radio>
            <el-radio :label="2" :value="2">实习</el-radio>
            <el-radio :label="3" :value="3">兼职</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="职位类别" prop="jobcategoryArr" required>
          <el-cascader
            v-model="positionForm.jobcategoryArr"
            :options="positionType"
            @change="handleChangeLb"
            :props="cascaderProps"
            placeholder="请选择职位类别"
            clearable
          ></el-cascader>
        </el-form-item>
        <el-row :gutter="10" type="flex">
          <el-form-item label="经验不限" prop="education">
            <el-select v-model="positionForm.experience" placeholder="不限">
              <el-option
                v-for="item in experienceList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="学历不限" prop="education">
            <el-select v-model="positionForm.education" placeholder="不限">
              <el-option
                v-for="item in educationalList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="招聘人数" prop="amount">
            <el-input
              v-model.number="positionForm.amount"
              placeholder="若干"
            ></el-input>
          </el-form-item>
        </el-row>
        <el-row :gutter="10">
          <el-form-item label="薪资待遇" prop="minWage">
            <el-row :gutter="10" type="flex">
              <el-input
                v-model="positionForm.minWage"
                style="width: 20%; margin-right: 5px"
                :placeholder="
                  positionForm.negotiable ? positionForm.minWage : ''
                "
                :disabled="positionForm.negotiable"
              ></el-input>
              -
              <el-input
                v-model="positionForm.maxWage"
                style="width: 20%; margin-left: 5px"
                :placeholder="
                  positionForm.negotiable ? positionForm.maxWage : ''
                "
                :disabled="positionForm.negotiable"
              ></el-input>
              <el-checkbox
                v-model="positionForm.negotiable"
                label=""
                style="margin-left: 10px"
                @change="handleNegotiableChange"
                >面议</el-checkbox
              >
            </el-row>
          </el-form-item>
        </el-row>
        <el-form-item label="工作地区" prop="citycategoryArr" required>
          <el-cascader
            v-model="positionForm.citycategoryArr"
            :options="areaList"
            @change="handleChange"
            :props="cascaderProps"
            placeholder="请选择工作地区"
            clearable
          ></el-cascader>
        </el-form-item>
        <el-form-item label="工作地址" prop="address">
          <el-input
            v-model="positionForm.address"
            placeholder="请输入详细地址"
            style="width: 35%"
          ></el-input>
        </el-form-item>
        <el-form-item label="职位描述" prop="content">
          <el-input
            v-model="positionForm.content"
            placeholder=""
            type="textarea"
            style="width: 50%"
            :rows="7"
          ></el-input>
        </el-form-item>
      </el-card>

      <el-card style="margin-top: 20px">
        <div style="padding: 20px 0; font-size: 16px">其他信息</div>
        <el-form-item label="岗位福利" prop="tags">
          <el-select
            v-model="positionForm.tags"
            multiple
            placeholder="请选择"
            :multiple-limit="10"
          >
            <el-option
              v-for="item in tags"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
          <el-button
            type="text"
            class="clear-btn"
            @click="clearTags"
            v-if="positionForm.tags && positionForm.tags.length"
          >
            清空
          </el-button>
        </el-form-item>
        <el-form-item label="联系方式" prop="useCompanyContact">
          <el-select v-model="positionForm.useCompanyContact" placeholder="使用企业资料联系方式">
            <el-option v-for="item in useCompanyContactList" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
          <!-- <el-select
            v-model="positionForm.useCompanyContact"
            placeholder="使用企业资料联系方式"
          >
            <el-option label="使用企业资料联系方式" :value="1"></el-option>
            <el-option label="使用其他联系方式" :value="2"></el-option>
          </el-select> -->
        </el-form-item>
        <el-form-item label="联系人" prop="contact" v-if="positionForm.useCompanyContact === 0">
          <el-input
            v-model="positionForm.contact"
            placeholder="请填写联系人"
            style="width: 35%"
          ></el-input>
        </el-form-item>
        <el-form-item label="联系手机" prop="mobile" v-if="positionForm.useCompanyContact === 0">
          <el-input
            v-model="positionForm.mobile"
            placeholder="请填写手机号"
            style="width: 35%"
            @input="handleMobileInput"
          ></el-input>
          <el-checkbox
            v-model="positionForm.needNotice"
            label="不对外显示仅接受通知"
            style="margin-left: 10px"
          ></el-checkbox>
        </el-form-item>
        <el-form-item label="企业固话" prop="telephone" v-if="positionForm.useCompanyContact === 0">
          <el-input
            v-model="positionForm.telephone"
            placeholder="请输入联系固话(格式:区区号+电话号)"
            style="width: 35%"
          ></el-input>
        </el-form-item>
        <el-form-item label="联系微信" prop="weixin" v-if="positionForm.useCompanyContact === 0">
          <el-input
            v-model="positionForm.weixin"
            placeholder="请填写微信号"
            style="width: 35%"
          ></el-input>
          <el-checkbox
            v-model="weixinSameAsMobile"
            label="同手机号"
            style="margin-left: 10px"
            @change="handleWeixinSameAsMobile"
          ></el-checkbox>
        </el-form-item>

        <el-form-item label="联系邮箱" prop="email" v-if="positionForm.useCompanyContact === 0">
          <el-input
            v-model="positionForm.email"
            placeholder="请输入邮箱号"
            style="width: 35%"
          ></el-input>
        </el-form-item>
        <el-form-item label="">
          <el-checkbox label="" v-model="positionForm.isSecrecy">
            联系方式保密（不想受到骚扰）
          </el-checkbox>
        </el-form-item>
        <el-form-item label="">
          <el-button type="primary" @click="postPosition">发布职位</el-button>
        </el-form-item>
      </el-card>
      <!-- <el-card style="margin-top: 20px">
        <div style="padding: 20px 0; font-size: 16px">联系方式</div>
    
  
        <el-form-item label="">
          <el-switch
            active-text="联系手机接收投递通知"
            inactive-text="接收通知"
          ></el-switch>
        </el-form-item>
        <div class="follow_wechat">
          <div>
            <vue-qr
              :text="codeText"
              :size="75"
              :margin="20"
              colorDark="black"
              backgroundColor="#f7f9fd"
              :logoSrc="lgoImg"
              logoScale="0.21"
              logoMargin="25px"
              :callback="getCode"
            ></vue-qr>
          </div>
          <div class="follow_wechat_rt">
            <div class="text1"></div>
            <div class="text2">
              随时随地接收简历投递通知，更有优秀人才精准推荐
            </div>
          </div>
        </div>
    
      </el-card>  -->
    </el-form>
  </div>
</template>

<script>
import VueQr from "vue-qr";
import {
  addPositionApi,
  selCategoryDistrictListApi,
  selCategoryJobListApi,
} from "@/api/position";
import { selTagListApi } from "@/api/qyManage";
import { mapGetters } from "vuex";
export default {
  components: { VueQr },
  data() {
    return {
      codeText: "https://blog.csdn.net/yuansusu_?spm=1000.2115.3001.53",
      positionForm: {
        source: 1,
        uid: "",
        companyId: "",
        nature: 1,
        jobname: "",
        address: "",
        category1: null,
        category2: null,
        category3: null,
        district1: null,
        district2: null,
        district3: null,
        maxWage: null,
        minWage: null,
        content: "",
        amount: null,
        ageNa: 0,
        // 工作地区
        citycategoryArr: [],
        // 职位类别
        jobcategoryArr: [],
        contact: "",
        customField1: "",
        customField2: "",
        customField3: "",
        department: "",
        // 	教育程度
        education: null,
        email: "",
        // 	工作经验
        experience: null,
        // isSecrecy
        isDisplay: 1,
        // 	是否显示
        isSecrecy: 1,
        mapLat: "0.000000",
        mapLng: "0.000000",
        mapZoom: 13,
        maxAge: "",
        minAge: "",
        // 是否需要通知
        needNotice: 1,
        // 是否可协商
        negotiable: false,
        qq: "",
        tags: [],
        // 电话号码
        telephone: "",
        // useCompanyContact
        useCompanyContact: 1,
        weixin: "",
        jobFairId: null,
      },
      areaList: [],
      positionType: [],
      tags: [],
      weixinSameAsMobile: true, // 默认勾选同手机号
      cascaderProps: {
        checkStrictly: true, // 设置为 true 以严格检查选中项
        label: "label",
        value: "value",
        emitPath: true, // 返回完整路径
        expandTrigger: "hover", // 悬停展开
        // 其他 props 属性...
      },
      // 经验要求
      experienceList: [
        { label: "不限", value: 0 },
        { label: "1年", value: 1 },
        { label: "2年", value: 2 },
        { label: "3年", value: 3 },
        { label: "3-5年", value: 4 },
        { label: "5-10年", value: 5 },
        { label: "10年以上", value: 6 },
      ],
      useCompanyContactList: [
        { label: "使用企业资料联系方式", value: 1 },
        { label: "使用其他联系方式", value: 0 },
      ],
      // 学历要求
      educationalList: [
        { label: "不限", value: 0 },
        { label: "初中", value: 1 },
        { label: "高中", value: 2 },
        { label: "中技", value: 3 },
        { label: "中专", value: 4 },
        { label: "大专", value: 5 },
        { label: "本科", value: 6 },
        { label: "硕士", value: 7 },
        { label: "博士", value: 8 },
        { label: "博士后", value: 9 },
      ],
      // 最小薪资
      minWageList: [
        { value: 500, label: "500元/月" },
        { value: 1000, label: "1000元/月" },
        { value: 1500, label: "1500元/月" },
        { value: 2000, label: "2000元/月" },
        { value: 2500, label: "2500元/月" },
        { value: 3000, label: "3000元/月" },
        { value: 3500, label: "3500元/月" },
        { value: 4000, label: "4000元/月" },
        { value: 4500, label: "4500元/月" },
        { value: 5000, label: "5000元/月" },
        { value: 5500, label: "5500元/月" },
        { value: 6000, label: "6000元/月" },
        { value: 6500, label: "6500元/月" },
        { value: 7000, label: "7000元/月" },
        { value: 7500, label: "7500元/月" },
        { value: 8000, label: "8000元/月" },
        { value: 8500, label: "8500元/月" },
        { value: 9000, label: "9000元/月" },
        { value: 9500, label: "9500元/月" },
        { value: 10000, label: "10000元/月" },
        { value: 10500, label: "10500元/月" },
        { value: 11000, label: "11000元/月" },
        { value: 11500, label: "11500元/月" },
        { value: 12000, label: "12000元/月" },
        { value: 12500, label: "12500元/月" },
        { value: 13000, label: "13000元/月" },
        { value: 13500, label: "13500元/月" },
        { value: 14000, label: "14000元/月" },
        { value: 14500, label: "14500元/月" },
        { value: 15000, label: "15000元/月" },
        { value: 20000, label: "20000元/月" },
        { value: 25000, label: "25000元/月" },
        { value: 30000, label: "30000元/月" },
        { value: 35000, label: "35000元/月" },
        { value: 40000, label: "40000元/月" },
        { value: 45000, label: "45000元/月" },
      ],
      maxWageList: [
        { value: 1000, label: "1000元/月" },
        { value: 1500, label: "1500元/月" },
        { value: 2000, label: "2000元/月" },
        { value: 2500, label: "2500元/月" },
        { value: 3000, label: "3000元/月" },
        { value: 3500, label: "3500元/月" },
        { value: 4000, label: "4000元/月" },
        { value: 4500, label: "4500元/月" },
        { value: 5000, label: "5000元/月" },
        { value: 5500, label: "5500元/月" },
        { value: 6000, label: "6000元/月" },
        { value: 6500, label: "6500元/月" },
        { value: 7000, label: "7000元/月" },
        { value: 7500, label: "7500元/月" },
        { value: 8000, label: "8000元/月" },
        { value: 8500, label: "8500元/月" },
        { value: 9000, label: "9000元/月" },
        { value: 9500, label: "9500元/月" },
        { value: 10000, label: "10000元/月" },
        { value: 10500, label: "10500元/月" },
        { value: 11000, label: "11000元/月" },
        { value: 11500, label: "11500元/月" },
        { value: 12000, label: "12000元/月" },
        { value: 12500, label: "12500元/月" },
        { value: 13000, label: "13000元/月" },
        { value: 13500, label: "13500元/月" },
        { value: 14000, label: "14000元/月" },
        { value: 14500, label: "14500元/月" },
        { value: 15000, label: "15000元/月" },
        { value: 20000, label: "20000元/月" },
        { value: 25000, label: "25000元/月" },
        { value: 30000, label: "30000元/月" },
        { value: 35000, label: "35000元/月" },
        { value: 40000, label: "40000元/月" },
        { value: 45000, label: "45000元/月" },
        { value: 50000, label: "50000元/月" },
      ],
      categoryType: "",
      districtType: [],
      rules: {
        jobname: [
          { required: true, message: "请输入职位名称", trigger: "blur" },
        ],
        address: [
          { required: true, message: "请输入工作地址", trigger: "blur" },
        ],
        category1: [
          { required: true, message: "请选择职位类别", trigger: "change" },
        ],
        category2: [
          { required: true, message: "请选择职位类别", trigger: "change" },
        ],
        category3: [
          { required: true, message: "请选择职位类别", trigger: "change" },
        ],
        district: [
          { required: true, message: "请选择职位地区", trigger: "change" },
        ],
        district1: [
          { required: true, message: "请选择职位地区", trigger: "change" },
        ],
        district2: [
          { required: true, message: "请选择职位地区", trigger: "change" },
        ],
        district3: [
          { required: true, message: "请选择职位地区", trigger: "change" },
        ],
        minWage: [
          {
            required: true,
            message: "请选择最小薪资",
            trigger: "change",
            validator: (rule, value, callback) => {
              if (!this.positionForm.negotiable) {
                if (!value) {
                  callback(new Error("请选择最小薪资"));
                } else {
                  callback();
                }
              } else {
                callback();
              }
            },
          },
        ],
        maxWage: [
          {
            required: true,
            message: "请选择最大薪资",
            trigger: "change",
            validator: (rule, value, callback) => {
              if (!this.positionForm.negotiable) {
                if (!value) {
                  callback(new Error("请选择最大薪资"));
                } else if (Number(value) <= Number(this.positionForm.minWage)) {
                  callback(new Error("最大薪资必须大于最小薪资"));
                } else {
                  callback();
                }
              } else {
                callback();
              }
            },
          },
        ],
        content: [
          { required: true, message: "请填写职位描述", trigger: "blur" },
          // { min: 20, message: "职位描述不能少于20个字", trigger: "blur" },
        ],
        contact: [
          { 
            required: true, 
            message: "请填写联系人", 
            trigger: "blur",
            validator: (rule, value, callback) => {
              if (this.positionForm.useCompanyContact === 0 && !value) {
                callback(new Error("请填写联系人"));
              } else {
                callback();
              }
            }
          },
          {
            min: 2,
            max: 20,
            message: "联系人长度在2-20个字符之间",
            trigger: "blur" 
          }
        ],
        mobile: [
          {
            required: true,
            message: "请填写联系手机",
            trigger: "blur",
            validator: (rule, value, callback) => {
              if (this.positionForm.useCompanyContact === 0 && !value) {
                callback(new Error("请填写联系手机"));
              } else {
                callback();
              }
            }
          },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: "请输入正确的手机号码",
            trigger: "blur",
            validator: (rule, value, callback) => {
              if (this.positionForm.useCompanyContact === 0 && value && !/^1[3-9]\d{9}$/.test(value)) {
                callback(new Error("请输入正确的手机号码"));
              } else {
                callback();
              }
            }
          }
        ],
        jobcategoryArr: [
          { required: true, message: "请选择职位类别", trigger: "change" },
          {
            validator: (rule, value, callback) => {
              if (!value || value.length < 2) {
                callback(new Error("请至少选择二级职位类别"));
              } else {
                callback();
              }
            },
            trigger: "change",
          },
        ],
        citycategoryArr: [
          { required: true, message: "请选择工作地区", trigger: "change" },
          {
            validator: (rule, value, callback) => {
              if (!value || value.length < 2) {
                callback(new Error("请至少选择二级工作地区"));
              } else {
                callback();
              }
            },
            trigger: "change",
          },
        ],
      },
    };
  },
  created() {
    // 检查路由参数
    const { source, id } = this.$route.query;
    console.log(source, id);
    if (source == 0) {
      // this.$alert("这是一段内容", "标题名称", {
      //   confirmButtonText: "确定",
      //   callback: (action) => {
      //     this.$message({
      //       type: "info",
      //       message: `action: ${action}`,
      //     });
      //   },
      // });
      this.$notify({
        title: "提示",
        message:
          "该岗位可以修改，但参加招聘会审核通过，那就需要联系人社进行撤销后才能修改岗位",
        duration: 0,
      });
      this.positionForm.source = Number(source); // 确保转换为数字
      this.positionForm.jobFairId = id;
      console.log("Source set to:", this.positionForm.source);
    }
    this.positionForm.uid = this.userId;
    this.positionForm.companyId = this.cid;
    this.selCategoryDistrictList();
    this.selCategoryJobList();
    this.selTagList();
  },
  computed: {
    ...mapGetters(["userId", "cid"]),
  },
  methods: {
    // 清空所有标签
    clearTags() {
      this.positionForm.tags = [];
    },
    // 获取标签列表
    async selTagList() {
      try {
        const res = await selTagListApi();
        this.tags = res.data;
      } catch (error) {
        console.error("获取岗位福利标签失败:", error);
      }
    },
    // 企业工作地区查询
    async selCategoryDistrictList() {
      try {
        const res = await selCategoryDistrictListApi();
        this.areaList = res.data[0].map((item) => ({
          label: item.name, // 父级项的 value 设置为 name
          value: item.id,
          children: item.children
            ? item.children.map((child) => ({
                label: child.name, // 子项的 label 设置为 name
                value: child.id, // 子项的 value 设置为 id 的字符串形式
                children: child.children.map((subDistrict) => ({
                  label: subDistrict.name, // 父级项的 value 设置为 name
                  value: subDistrict.id,
                })), // 子项的 children 默认为空数组，如果需要更深层次的数据结构，可以在这里添加逻辑
              }))
            : [], // 如果没有 categoryDistricts，children 设置为空数组
        }));
      } catch (error) {
        console.error("获取地区列表失败:", error);
      }
    },
    // 获取职位类别数据
    async selCategoryJobList() {
      try {
        const res = await selCategoryJobListApi();
        this.positionType = res.data[0].map((item) => ({
          label: item.name,
          value: item.id,
          children: item.children
            ? item.children.map((child) => ({
                label: child.name,
                value: child.id,
                children: child.children.map((subDistrict) => ({
                  label: subDistrict.name,
                  value: subDistrict.id,
                })),
              }))
            : [],
        }));
      } catch (error) {
        console.error("获取职位类别失败:", error);
      }
    },
    // 职位地区改变的时候
    handleChange(value) {
      if (value) {
        this.positionForm.district1 = value[0];
        this.positionForm.district2 = value[1];
        this.positionForm.district3 = value[2] || 0;
        // 触发表单验证
        this.$refs.positionFormRef.validateField("citycategoryArr");
      }
    },
    // 选择职位类别改变的时候
    handleChangeLb(value) {
      if (value) {
        this.positionForm.category1 = value[0];
        this.positionForm.category2 = value[1];
        this.positionForm.category3 = value[2];
        // 触发表单验证
        this.$refs.positionFormRef.validateField("jobcategoryArr");
      }
    },
    // 处理手机号输入
    handleMobileInput(value) {
      if (this.weixinSameAsMobile) {
        this.positionForm.weixin = value;
      }
    },
    // 处理同手机号复选框变化
    handleWeixinSameAsMobile(checked) {
      if (checked) {
        this.positionForm.weixin = this.positionForm.mobile;
      }
    },
    // 处理面议复选框变化
    handleNegotiableChange(checked) {
      if (checked) {
        // 如果勾选面议，保留原值但禁用输入
        this.positionForm.minWage = this.positionForm.minWage || "";
        this.positionForm.maxWage = this.positionForm.maxWage || "";
      }
    },
    // 提交职位
    postPosition() {
      this.$refs.positionFormRef.validate(async (valid) => {
        if (valid) {
          // 额外验证职位类别和工作地区是否选择完整
          if (!this.positionForm.category1 || !this.positionForm.category2) {
            this.$message.error("请选择完整的职位类别");
            return false;
          }
          if (!this.positionForm.district1 || !this.positionForm.district2) {
            this.$message.error("请选择完整的工作地区");
            return false;
          }

          const formData = {
            ...this.positionForm,
            // 确保 tags 是数字数组
            tags: this.positionForm.tags.map((tag) => Number(tag)),
            // 转换 boolean 到数字
            needNotice: Number(this.positionForm.needNotice),
            isSecrecy: Number(this.positionForm.isSecrecy),
            weixinSameAsMobile: Number(this.weixinSameAsMobile),
            negotiable: Number(this.positionForm.negotiable),

            // 确保其他字段为数字类型
            nature: Number(this.positionForm.nature),
            experience: Number(this.positionForm.experience),
            education: Number(this.positionForm.education),
            amount: Number(this.positionForm.amount),
            minWage: this.positionForm.negotiable
              ? 0
              : Number(this.positionForm.minWage),
            maxWage: this.positionForm.negotiable
              ? 0
              : Number(this.positionForm.maxWage),
            useCompanyContact: Number(this.positionForm.useCompanyContact),
            uid: Number(this.positionForm.uid),
          };
          try {
            const res = await addPositionApi(formData);
            if (res.code === 1) {
              this.$message.success("发布成功");
              this.$refs.positionFormRef.resetFields();
              this.$router.back();
            } else {
              this.$message.error(res.msg || "发布失败");
            }
          } catch (error) {
            console.error(error);
            this.$message.error("发布失败");
          }
        } else {
          this.$message.error("请完善信息");
          return false;
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.Tips_text {
  padding: 16px 0;
  font-size: 11px;
  color: #846d39;
  background: #fefce8;
  margin-bottom: 20px;
}
.clear {
  text-decoration-line: none;
  cursor: pointer;
  color: rgb(3, 169, 244);
  padding-left: 10px;
}
.follow_wechat {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  width: 584px;
  height: 98px;
  background: #f7f9fd;
  opacity: 0.8;
  border-radius: 2px;
  margin: 0 0 23px 32px;
  box-sizing: border-box;
  padding: 0 0 0 34px;
  .follow_wechat_rt {
    margin-left: 45px;
    font-size: 14px;
    color: #1e1e1e;
    .text1 {
      width: 130px;
      height: 14px;
      background: url()
        50% no-repeat;
      background-size: 100% 100%;
      margin-bottom: 13px;
      position: relative;
      &:after {
        content: "";
        display: block;
        width: 100%;
        height: 7px;
        background: #409eff;
        opacity: 0.2;
        position: absolute;
        bottom: -4px;
      }
    }
  }
}
</style>
